<!--
 * @Description: 栈思路
 * @Author: wangqi
 * @Date: 2021-06-11 11:32:47
 * @LastEditTime: 2021-06-11 12:19:02
-->

<script>
    // 试编写“智能重复”smartRepeat函数，实现：
    // 将3[abc]变为abcabcabc
    // 将3[2[a]2[b]]变为aabbaabbaabb  
    // 将2[1[a]3[b]2[3[c]4[d]]]变为abbbcccddddcccddddabbbcccddddcccdddd

    function smartRepeat(templateStr) {
        // 指针
        let index = 0;
        // 数字栈
        let stack1 = [];
        // 字母栈
        let stack2 = [];
        // 剩余部分
        let res = templateStr;
        while (index < templateStr.length - 1) {
            res = templateStr.slice(index);
            if (/^\d+\[/.test(res)) {
                let num = Number(res.match(/^(\d+)\[/)[1]);
                stack1.push(num);
                stack2.push('');
                index += num.toString().length + 1;

            } else if (/^\w+\]/.test(res)) {
                let word = res.match(/^(\w+)\]/)[1];
                stack2[stack2.length - 1] = word;
                index += word.length;

            } else if (res[0] == ']') {
                let num = stack1.pop();
                let word = stack2.pop();
                stack2[stack2.length - 1] += word.repeat(num);
                index++;
            }
        }
        return stack2[0].repeat(stack1[0])
        // console.log(index, stack1, stack2);
    };

    var result = smartRepeat('3[2[3[a]1[b]]4[d]]');
    // var result = smartRepeat('3[2[a]2[b]]');
    console.log(result);
</script>